﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Telerik.Web.UI;

public partial class SiteWorx_CreateNewPage : System.Web.UI.Page
{

    #region Create New Page

    public Asah.SiteWorx.SiteMap.Page MyPage
    {
        get
        {
            if (Session["MyPage"] == null)
                Session["MyPage"] = Asah.SiteWorx.SiteMap.Page.NewPage();
            return (Asah.SiteWorx.SiteMap.Page)Session["MyPage"];
        }
        set
        {
            Session["MyPage"] = value;
        }
    }

    protected void cdsPage_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = MyPage;
    }

    protected void cdsPage_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {
        Csla.Data.DataMapper.Map(e.Values, MyPage);
        SavePage();
    }

    private void SavePage()
    {
        if (MyPage.IsValid)
        {
            MyPage.Save();
            ScriptManager.RegisterStartupScript(this, Page.GetType(), "NewPage", "GoToNewPage('../" + MyPage.FileName + ".aspx" + "');", true);
            MyPage = null;
        }
        else
        {
            CustomValidator validator;
            foreach(Csla.Validation.BrokenRule rule in MyPage.BrokenRulesCollection)
            {
                validator = new CustomValidator();
                validator.ErrorMessage = rule.Description;
                validator.IsValid = false;
                Page.Validators.Add(validator);
            }
        }
    }

    protected void fvNewPage_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "Cancel")
            ScriptManager.RegisterStartupScript(this, Page.GetType(), "CloseScript", "CloseOnReload();", true);
    }

    protected void lstLayout_Load(object sender, EventArgs e)
    {
        LoadMasterLayouts();
    }

    private void LoadMasterLayouts()
    {
        string[] masterLayouts = null;
        char[] pipeSplitter = { '|' };
        char[] commaSplitter = { ',' };

        masterLayouts = ConfigurationManager.AppSettings["AvailableMasterLayouts"].ToString().Split(pipeSplitter);
        foreach (string masterLayout in masterLayouts)
        {
            string[] layoutProperties = masterLayout.Split(commaSplitter);
            ((RadComboBox)fvNewPage.FindControl("lstLayout")).Items.Add(new RadComboBoxItem(layoutProperties[1].ToString(), 
                                                                        layoutProperties[0].ToString()));
        }
    }

    #endregion

}